package com.example.myapplication;

import android.app.Activity;
import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStore;
import androidx.lifecycle.ViewModelStoreOwner;

import com.tencent.mmkv.MMKV;

public class MyApplication extends Application implements ViewModelStoreOwner {


    private static MyApplication instance;
    private ViewModelStore mAppViewModelStore;
    private ViewModelProvider.Factory mFactory;

    @Override
    public void onCreate() {
        super.onCreate();
         instance = this;
        mAppViewModelStore = new ViewModelStore();
        //初始化腾讯MMKV(数据存储)
        MMKV.initialize(this,"/sdcard/mmkv");
    }

    public static Application getInstance(){
        return instance;
    }

    @NonNull
    @Override
    public ViewModelStore getViewModelStore() {
        return mAppViewModelStore;
    }


    /**
     * 对外面提供唯一的一份 ViewModelProvider
     * @param activity
     * @return
     */
    public static ViewModelProvider getViewModelProvider(Activity activity) {

        return new ViewModelProvider((MyApplication) activity.getApplicationContext(),
                ((MyApplication) activity.getApplicationContext()).getAppFactory(activity));

    }


    /**
     * 内部享有   就是为了拿到  ViewModelProvider.Factory
     * @param activity
     * @return
     */
    private ViewModelProvider.Factory getAppFactory(Activity activity) {

        Application application = checkApplication(activity);
        if (mFactory == null) {
            mFactory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
        }
        return mFactory;
    }

    private Application checkApplication(Activity activity) {
        return this;
    }
}
